/**
 * 
 */
package vanhoc.android.mediakool;

import java.io.File;
import java.util.ArrayList;

import vanhoc.android.mediakool.R;
import vanhoc.android.mediakool.custom.adapter.SongListAdapter;
import vanhoc.android.mediakool.db.DatabaseHelper;
import vanhoc.android.medialcool.helper.AlertDialogManager;
import vanhoc.android.medialcool.item.data.PlaylistItemData;
import vanhoc.android.medialcool.item.data.SongItemData;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ListView;

/**
 * @author Administrator
 *
 */
public class SongListenningActivity extends Activity implements OnItemClickListener, OnItemLongClickListener {
	ListView listSong;
	
	private DatabaseHelper databaseHelper	=	new DatabaseHelper(this);
	
	ArrayList<SongItemData> arrListSong;
	
	/**
	 * fieldName :  ten truong nam trong songs table - cai ma se dua vao de lay ve ds se phat nhac (vd:  album  hoac artist hoac playlist ... hoac all)
	 */
	private String fieldName;
	
	
	/**
	 * Gia tri cua  fieldName
	 * Vd: album(fieldName) = mp3.zing.vn -> lay ve ds nhung bai hat nam trong mp3.zing.vn (dc gui tu AlbumActivity)
	 * vd: song(fieldName) = all  -> lay ve ds phat nhac la tat ca cac  bai hat co trogn sdcard (dc gui tu AllSOngsActivity)
	 */
	private String fieldValue;
	
	
	private int playlist_id = 0;
	
	//id bai hat dang hat, mac dinh chua co bai hat nao hat thi gan  = 0
	int songPlayingID = 0;
	
	/**
	 * Dialog alert option for a song
	 */
	Dialog featureDialog;
	
	Dialog dialogPlaylist;
	
	/**
	 * danh sach cac playlist (khi user chon menu\add to playlist
	 */
	ArrayList<PlaylistItemData> arrPlaylist;
	
	
	ListView lvPlaylist;
	
	
	int songSelectedID;
	
	String songSelectedTitle;
	
	AlertDialogManager alertDialog = new AlertDialogManager();
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.song);
		
		
		//Lay ve du lieu tu intent
		getIntentData();
		
		//lay ve danh sach bai hat cung playlist voi bai hat dang play
		getCurrentListSong();
				
		initListView();
	}
	
	
	
	private void initListView() {
		listSong = (ListView) findViewById(R.id.listSong);
		
		//init Adapter
		SongListAdapter songListAdapter = new SongListAdapter(getApplicationContext(), R.id.listSong, arrListSong);
		
		//gui id cua bai hat dang hat sang Adapter de khi hien thi list song len listview, thi bai hat dang hat dc thay bang 1 icon khac
		songListAdapter.setSongPlayingID(this.songPlayingID);
		
		
		//Set Adapter cho listview
		listSong.setAdapter(songListAdapter);
		
		//set onClick
		listSong.setOnItemClickListener(this);
		listSong.setOnItemLongClickListener(this);
	}



	/**
	 * Lay du lieu dc gui tu MusicPlayerActivity thong qua intent
	 */
	private void getIntentData() {
		this.fieldName	=	getIntent().getExtras().getString("FIELDNAME");
		
		this.fieldValue	=	getIntent().getExtras().getString("FIELDVALUE");
		
		//playlist id
		this.playlist_id = getIntent().getExtras().getInt("PLAYLIST_ID");
		
		//lay ve id cua bai hat dang choi quan intent (neu co) -> them icon cho biet la co 1 bai hat dang hat trong album nao
		this.songPlayingID	=	 getIntent().getExtras().getInt("songIdPlaying");
	}


	/**
	 * Lay ve ds dang phat nhac
	 * @return
	 */
	private void getCurrentListSong() {
		if (this.playlist_id > 0) {
			this.arrListSong = getCurrentListSongByPlaylist(this.playlist_id);
		}else{
			//kiem tra fieldName xem lay ve ds nhac theo truong nao, va dua vao fieldValue de biet dc dieu kien loc du lieu
			if (this.fieldName.equals("song")) { //lay ve tca cac bai hat trong sdcard (nghia la truoc do nguoi dung chon nghe nhac tu AllSongsActivity)
				this.arrListSong = getAllSong();
			}else{ //lay ve ds id cua nhung bai hat theo album hoac artist,genre
				this.arrListSong = getCurrentListSongByGroup();
			}
		}
	}

	

	/**
	 * Lay ve ds dang phat theo album (hoac artist hoac genre)
	 */
	private ArrayList<SongItemData> getCurrentListSongByGroup() {
		ArrayList<SongItemData> currentListSong = new ArrayList<SongItemData>();
		databaseHelper.openToRead();
		currentListSong = databaseHelper.getSongListByTagName(fieldName,fieldValue);
		databaseHelper.close();
		
		return currentListSong;
	}



	/**
	 * Lay ve danh sach bai hat theo playlist
	 * @param playlistId : chua bai hat dang hat
	 * @return
	 */
	public ArrayList<SongItemData> getCurrentListSongByPlaylist(int playlistId){
		ArrayList<SongItemData> currentListSong = new ArrayList<SongItemData>();
		
		databaseHelper.openToRead();
		Cursor cursor = databaseHelper.getListSongByPlaylist(playlistId);
		cursor.moveToFirst();
		for (int i = 0; i < cursor.getCount(); i++) {
			SongItemData item = new SongItemData();
			item.setID(Integer.parseInt(cursor.getString(0)));
			item.setName(cursor.getString(1));
			item.setAlbum(cursor.getString(2));
			item.setArtist(cursor.getString(3));
			item.setGenre(cursor.getString(4));
			item.setDuration(cursor.getString(5));
			item.setPath(cursor.getString(6));
			
			currentListSong.add(item);
			cursor.moveToNext();
		}
		databaseHelper.close();
		
		return currentListSong;
	}

	
	/**
	 * Lay ve tat ca bai hat trong sdcard
	 * @return
	 */
	public ArrayList<SongItemData> getAllSong(){
		ArrayList<SongItemData> currentListSong = new ArrayList<SongItemData>();
		
		databaseHelper.openToRead();
		Cursor cursor = databaseHelper.getFullInfoAllSong();
    	startManagingCursor(cursor);
    	cursor.moveToFirst();
    	for (int i = 0; i < cursor.getCount(); i++) {
    		SongItemData songData = new SongItemData();
    		songData.setID(Integer.parseInt(cursor.getString(0)));
    		songData.setName(cursor.getString(1));
    		songData.setAlbum(cursor.getString(2));
    		songData.setArtist(cursor.getString(3));
    		songData.setGenre(cursor.getString(4));
    		songData.setDuration(cursor.getString(5));
    		songData.setPath(cursor.getString(6));
    		
    		//adding to array list song
    		currentListSong.add(songData);
    		cursor.moveToNext();
		}
    	databaseHelper.close();
    	
    	return currentListSong;
	}
	
	private void playSong(int songID) {
		Intent intent = new Intent(SongListenningActivity.this, MusicPlayerActivity.class);
		intent.putExtra("FIELDNAME", this.fieldName);
		intent.putExtra("FIELDVALUE", this.fieldValue);
		intent.putExtra("PLAYLIST_ID", this.playlist_id);
		intent.putExtra("songID", songID);
		startActivity(intent);
	}
	
	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
		int songID = arrListSong.get(position).getID();
		if (songID != this.songPlayingID) {
			playSong(songID);
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
		songSelectedID = arrListSong.get(position).getID();
		songSelectedTitle = arrListSong.get(position).getName();
		//hien thi cac tuy chon dang listview 
		showFeatureList();
		
		return false;
	}


	private void showFeatureList() {
		featureDialog = new Dialog(SongListenningActivity.this,0);
		featureDialog.setTitle(songSelectedTitle);
		featureDialog.setContentView(R.layout.listview);
		featureDialog.show();
		
		final String[] options = getResources().getStringArray(R.array.list_feature_for_song_listening);
		
		//list view
		ListView listOption = (ListView) featureDialog.findViewById(R.id.listView);
		
		ArrayAdapter<String>  adapter = new ArrayAdapter<String>(SongListenningActivity.this, android.R.layout.simple_list_item_1, options);
		listOption.setAdapter(adapter);
		
		listOption.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?>  parent, View v, int position,long id) {
				switch (position) {
					case 0:
						playSong(songSelectedID);
						break;
					case 1:
						editSongTitle(songSelectedTitle);
						break;
					case 2:
						//set ringtone
						break;
					case 3: //xoa 1 bai hat
						//Neu la bai hat dang hat thi khong xoa dc. Neu khong phai thi xoa dc
						deleteSelectedSong();
						break;
					default:
						break;
				}			
			}
		});
	}

	protected void deleteSelectedSong() {
		//kiem tra xem id cua bai hat dang hat co phai la bai hat da chon de xoa hay ko?Neu khong thi cho xoa. Neu dung thi khong cho xoa
		if (this.songSelectedID == this.songPlayingID) {
			alertDialog.showAlertDialog(SongListenningActivity.this, getString(R.string.error),
					getString(R.string.cannot_delete_song), false);
		}else{
			confirmDeleteCurrentSong();
		}
	}
	
	
	/**
     * Confirm 
     */
    public void confirmDeleteCurrentSong(){
    	AlertDialog alert = new AlertDialog.Builder(SongListenningActivity.this).create();
		alert.setTitle("Do you want to delete this song");
		// Setting OK Button
		alert.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                	deleteSong();
    				initListView();
    				featureDialog.dismiss();
                }
        });
		
		alert.setButton2("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				featureDialog.dismiss();
			}
		});
		
		alert.show();
    }
    
    /**
     * delete
     */
    protected void deleteSong() {
		//xoa trong sdcard
    	deleteSongFromSdcard();
    	
    	//xoa trong csdl
    	deleteSongData();
	}
    
    /**
     * Xoa du lieu 1 bai hat trong database
     */
	private void deleteSongData() {
		databaseHelper.openToWrite();
		databaseHelper.deleteSong(songSelectedID);
		databaseHelper.close();
	}
	
	
	/**
	 * Xoa file mp3 tu trong sdcard
	 */
	private void deleteSongFromSdcard() {
		//co id cua bai hat da chon, truy van vao csdl de lay ve path cua no
		databaseHelper.openToRead();
		String path = databaseHelper.getSongPath(songSelectedID);
		databaseHelper.close();
		
		File mp3File = new File(path);
		if (mp3File.delete()) {
			Toast.makeText(getApplicationContext(), R.string.deleted_success, Toast.LENGTH_LONG).show();
		}else{
			Toast.makeText(getApplicationContext(), R.string.deleted_unsuccess, Toast.LENGTH_LONG).show();
		}
		featureDialog.dismiss();
	}

	// chinh sua ten bai hat
	protected void editSongTitle(String songTitle) {
		final Dialog dialogEditSongTitle = new Dialog(SongListenningActivity.this, 0);
		dialogEditSongTitle.setTitle(getResources().getString(R.string.edit));
		dialogEditSongTitle.setContentView(R.layout.add_edit_title_layout);
		dialogEditSongTitle.getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
		dialogEditSongTitle.show();
		
		//lay ve cac thanh phan cua layout add_playlist_layout thogn qua dialogAddPlaylist
		final EditText inputTitle 			= (EditText) dialogEditSongTitle.findViewById(R.id.txtTitle);
		inputTitle.setText(songSelectedTitle);
		final Button btnSave 				= (Button) dialogEditSongTitle.findViewById(R.id.btnSave);
		Button btnCancel 					= (Button) dialogEditSongTitle.findViewById(R.id.btnCancel);
		
		//set onclickListener for btnSave
		btnSave.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				String newSongTitle = inputTitle.getText().toString();
				if (newSongTitle.equals(null) || newSongTitle.equals("")) {
					alertDialog.showAlertDialog(SongListenningActivity.this, getString(R.string.error),
												getString(R.string.please_enter_song_title), false);
				}else{
					updateSongTitle(newSongTitle);
					dialogEditSongTitle.dismiss();
				}
			}
		});
		/*set onclickListener for btnSave*/
		btnCancel.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				dialogEditSongTitle.dismiss();
				featureDialog.dismiss();
				initListView();
			}
		});
	}
	
	/**
	 * Update new title
	 * @param newSongTitle
	 */
	protected void updateSongTitle(String newSongTitle) {
		databaseHelper.openToWrite();
		databaseHelper.updateSongTitle(songSelectedID,newSongTitle);
		databaseHelper.close();
		
		Toast.makeText(getApplicationContext(), R.string.successfully, Toast.LENGTH_LONG).show();
	}

}
